// 统计页面停留时间
let enterTime = '';
let outTime = '';
let stayTime = '';
import {
	savePageRecord
} from '@/apis/apis.js'
import {
	dateFormat
} from '@/utils/date.js'
export default {
	data() {
		return {
			// 需要被统计的页面列表
			pageList: [{
				page: 'pages/mine/views/vip/vip',
				pageType: 1
			}, {
				page: 'pages/mine/views/yield/yield',
				pageType: 2
			}, {
				page: 'pages/mine/views/create/center',
				pageType: 3
			}, {
				page: 'pages/topic/topic',
				pageType: 4
			}],
		};
	},
	onShow() {
		// 用户进入时间
		enterTime = new Date();
	},
	onHide() {
		this.dwellTime()
		// console.log('页面隐藏');
	},
	onUnload() {
		this.dwellTime()
		// console.log('页面卸载');
	},
	methods: {
		//判断当前页面时候需要统计
		judeCurrentPage() {
			let curRoute = this.$mp.page.route;
			let page = this.pageList.filter(v => v.page === curRoute)
			return page.length > 0 && page[0]
		},
		// 统计时间
		dwellTime() {
			const token = uni.getStorageSync('token');
			let page = this.judeCurrentPage()
			if (!page) return
			// 用户退出时间
			outTime = new Date();
			//停留时间(毫秒)
			stayTime = outTime.getTime() - enterTime.getTime();
			let data = {
				pageType: page.pageType,
				startTime: dateFormat(enterTime, 'yyyy-MM-dd hh:mm:ss'),
				endTime: dateFormat(outTime, 'yyyy-MM-dd hh:mm:ss'),
				timer: stayTime,
			}
			if (token) {
				savePageRecord(data).then(response => {
					// console.log('统计成功：',response)
				}).catch(err => {
					console.log('统计异常：', err)
				})
			}

		},
	}

};
